
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score

# 生成训练样本
X, y = make_blobs(n_samples=10000, n_features=10, centers=100)

# 创建决策树模型并进行 5 折交叉验证
dtc = DecisionTreeClassifier(max_depth=None)
scores_dtc = cross_val_score(dtc, X, y, cv=5)
print(scores_dtc)

# 创建随机森林模型并进行 5 折交叉验证
rfc = RandomForestClassifier(n_estimators=10, max_depth=None)
scores_rfc = cross_val_score(rfc, X, y, cv=5)
print(scores_rfc)

# 设置柱状图的横坐标
ind = np.arange(len(scores_dtc))
width = 0.35

# 绘制柱状图
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, scores_dtc, width, label=\'DecisionTree\')
rects2 = ax.bar(ind + width/2, scores_rfc, width, label=\'RandomForest\')

# 设置图表标签和标题
ax.set_ylabel(\'Accuracy\')
ax.set_title(\'Accuracy Comparison of Decision Tree and Random Forest\')
ax.set_xticks(ind)
ax.set_xticklabels((\'1\', \'2\', \'3\', \'4\', \'5\'))
ax.legend()

# 在柱状图上添加数值标签
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate(\'{}\\\'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords=\


offset points\"),
                    ha=\'center\', va=\'center\')
autolabel(rects1)
autolabel(rects2)

# 显示图表
plt.show()


